/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */
import * as path from 'path';

import { ModuleJson } from '../../../../src/options/configure/module-json-options';
import { updateElementInArrayByUniqueKey } from '../common';

import { BaseModifier } from './base-modifier';
import AbilityObj = ModuleJson.AbilityObj;
import ExtensionAbilityObj = ModuleJson.ExtensionAbilityObj;
import MetadataObj = ModuleJson.MetadataObj;
import ModuleOptObj = ModuleJson.ModuleOptObj;
import RequestPermissionObj = ModuleJson.RequestPermissionObj;

/**
 * 修改指定模块的module.json5
 */
export class ModuleJsonModifier extends BaseModifier {
  protected jsonObject!: ModuleOptObj;

  constructor(cwd: string, moduleName: string, target = 'main') {
    super(path.resolve(cwd, moduleName, 'src', target, 'module.json5'));
  }

  public getAbilities(): AbilityObj[] | undefined {
    return this.jsonObject.module.abilities;
  }

  public getExtensionAbilities(): AbilityObj[] | undefined {
    return this.jsonObject.module.extensionAbilities;
  }

  public setExtensionAbilities(abilities: ExtensionAbilityObj[] | undefined) {
    this.jsonObject.module.extensionAbilities = abilities;
    return this;
  }

  public getAbilityByName(name: string): AbilityObj | null {
    if (this.jsonObject.module.abilities !== undefined) {
      for (const ability of this.jsonObject.module.abilities) {
        if (ability.name === name) {
          return ability;
        }
      }
    }
    return null;
  }

  public updateAbility(ability: AbilityObj) {
    this.jsonObject.module.abilities = updateElementInArrayByUniqueKey(this.jsonObject.module.abilities, ability);
    return this;
  }

  public setDeviceType(deviceTypes: string[]) {
    this.jsonObject.module.deviceTypes = deviceTypes;
    return this;
  }

  public setMainElement(mainElement: string | undefined) {
    this.jsonObject.module.mainElement = mainElement;
    return this;
  }

  public setMetaData(metaData: MetadataObj[]) {
    this.jsonObject.module.metadata = metaData;
    return this;
  }

  public setRequestPermissions(requestPermissions: RequestPermissionObj[]) {
    this.jsonObject.module.requestPermissions = requestPermissions;
    return this;
  }

  public setAbilityName(abilityName: string, newName: string) {
    const abilityByName = this.getAbilityByName(abilityName);
    this.jsonObject.module.abilities?.forEach(ability => {
      if (ability === abilityByName) {
        abilityByName.name = newName;
      }
    });
    return this;
  }
}
